<template>
  <div class="order-list-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>我的订单</h3>
        </div>
      </template>

      <!-- 订单列表 -->
      <el-table :data="orderList" style="width: 100%" v-loading="loading">
        <el-table-column label="操作" width="100" fixed="left">
          <template #default="{ row }">
            <el-button
              size="small"
              @click="showDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="reservationId" label="订单号" width="180" />
        <el-table-column prop="roomName" label="会议室" />
        <el-table-column label="使用时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.reservationDate) }} {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="参会人数">
          <template #default="{ row }">
            {{ row.participants }}人
          </template>
        </el-table-column>
        <el-table-column label="设备需求">
          <template #default="{ row }">
            {{ row.requiredEquipment || '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="reservationStatus" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.reservationStatus)">
              {{ getStatusText(row.reservationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              v-if="(row.reservationStatus === 'pending' || row.reservationStatus === 'confirmed')"
              type="danger" 
              size="small"
              @click="handleCancel(row)"
            >
              取消预订
            </el-button>
            <el-button 
              v-if="row.reservationStatus === 'pending'"
              type="primary" 
              size="small"
              @click="handlePay(row)"
            >
              立即支付
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
    >
      <template v-if="selectedOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.reservationId }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.reservationStatus)">
              {{ getStatusText(selectedOrder.reservationStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会议室">{{ selectedOrder.roomName }}</el-descriptions-item>
          <el-descriptions-item label="参会人数">{{ selectedOrder.participants }}人</el-descriptions-item>
          <el-descriptions-item label="使用日期">{{ formatDate(selectedOrder.reservationDate) }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">
            {{ formatTime(selectedOrder.startTime) }} - {{ formatTime(selectedOrder.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="设备需求">{{ selectedOrder.requiredEquipment || '无' }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ currentTotalPrice }}</el-descriptions-item>
          <el-descriptions-item label="支付期限" v-if="selectedOrder.paymentDeadline">
            {{ formatDateTime(selectedOrder.paymentDeadline) }}
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>

    <!-- 取消预订对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消预订"
      width="500px"
    >
      <template v-if="selectedOrder">
        <el-alert
          title="退款规则"
          type="warning"
          :closable="false"
          class="mb-4"
        >
          <p>1. 提前72小时取消：退还全款</p>
          <p>2. 提前48小时取消：退还75%</p>
          <p>3. 提前24小时取消：退还25%</p>
        </el-alert>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.reservationId }}</el-descriptions-item>
          <el-descriptions-item label="会议室">{{ selectedOrder.roomName }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">
            {{ formatDate(selectedOrder.reservationDate) }} {{ formatTime(selectedOrder.startTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="支付金额">
            {{ currentTotalPrice }} 
          </el-descriptions-item>
        </el-descriptions>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelling">
            确认取消预订
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="payDialogVisible"
      title="订单支付"
      width="400px"
      :close-on-click-modal="false"
    >
      <template v-if="selectedOrder">
        <el-result
          icon="info"
          title="待支付"
          sub-title="请选择支付方式完成支付"
        >
          <template #extra>
            <div class="pay-amount">支付金额：<span class="price">¥{{ currentTotalPrice }}</span></div>
            <el-radio-group v-model="payMethod" class="pay-methods">
              <el-radio label="wechat">支付宝支付</el-radio>
            </el-radio-group>
            <el-button type="primary" @click="confirmPay" :loading="paying">确认支付</el-button>
          </template>
        </el-result>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getSessionStorage } from '../../utils/common'
import { getOrderList, payOrder ,getTotalPrice} from '../../api/orderApi'
import { createCancellationRequests } from '../../api/cancleOrderApi'

const loading = ref(false)
const detailDialogVisible = ref(false)
const cancelDialogVisible = ref(false)
const payDialogVisible = ref(false)
const selectedOrder = ref(null)
const payMethod = ref('wechat')
const paying = ref(false)
const cancelling = ref(false)
const customerId = ref(getSessionStorage("customerId"))
const orderList = ref([])

const currentReservationId = ref(0)
const currentHourlyRentalPrice = ref(0)
const currentTotalPrice = ref(0)


// 获取订单列表
const fetchOrderList = async () => {
  if (!customerId.value) {
    ElMessage.error('用户未登录')
    return
  }
  loading.value = true
  try {
    const response = await getOrderList(customerId.value)
    console.log(customerId.value)
    if (response.flag) {
      console.log(response)
      orderList.value = (response.result || []).filter(Boolean)
    } else {
      ElMessage.error(response.reason || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取总价
const getReservationTotalPrice = async (reservationId) => {
  try{
    console.log(reservationId);
    const params={
      reservationId:reservationId
    }
    const response = await getTotalPrice(params)
    console.log(response);
    if(response.flag){
      currentTotalPrice.value = response.result
    }else{
      ElMessage.error(response.reason || '获取总价失败')
    }
  }catch(error){
    ElMessage.error('获取总价失败')
  }

}

// 在组件挂载时获取订单列表
onMounted(() => {
  fetchOrderList()
})

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

const formatDateTime = (datetime) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm:ss') : ''
}

const formatTime = (time) => {
  return time ? dayjs(time).format('HH:mm') : ''
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    confirmed: 'success',
    cancelled: 'info'
  }
  return map[status]
}

const getStatusText = (status) => {
  const map = {
    pending: '待支付',
    confirmed: '已支付',
    cancelled: '已取消'
  }
  return map[status]
}

const showDetail = (row) => {
  selectedOrder.value = row
  detailDialogVisible.value = true
  getReservationTotalPrice(row.reservationId)
}

const handlePay = (row) => {
  selectedOrder.value = row
  currentReservationId.value = row.reservationId
  currentHourlyRentalPrice.value = row.hourlyRentalPrice
  getReservationTotalPrice(row.reservationId)

  payDialogVisible.value = true
}

async function confirmPay(){
  paying.value = true
  // TODO: 调用支付接口
  try{
    const params = {
      reservationId: currentReservationId.value
    }
    const response = await payOrder(params)
    const blob = new Blob([response],{type:"text/html"});
    const url = URL.createObjectURL(blob)
    window.open(url,'_self')
    ElMessage.success('支付成功')
    // router.push('/customer/orderList')

    // if(response.flag){
    //   paying.value = false
    //   payDialogVisible.value = false
    //   ElMessage.success('支付成功')
    //   router.push('/customer/orderList')
    // }else{
    //   paying.value = false
    //   ElMessage.error(response.reason || '请求失败')
    // }
  }catch(error){
    ElMessage.error('网络错误：' + error.message)
    console.error("支付订单错误:", error)
    router.push('/customer/roomList')
  }
}


const handleCancel = (row) => {
  selectedOrder.value = row
  cancelDialogVisible.value = true
  getReservationTotalPrice(row.reservationId)
  console.log(row);

  
}

const calculateRefund = (order) => {
  const useDateTime = dayjs(`${order.reservationDate} ${order.startTime}`)
  const now = dayjs()
  const hours = useDateTime.diff(now, 'hour')
  
  if (hours >= 72) {
    return order.totalPrice
  } else if (hours >= 48) {
    return order.totalPrice * 0.75
  } else if (hours >= 24) {
    return order.totalPrice * 0.25
  }
  return 0
}

const confirmCancel = async () => {
  cancelling.value = true

  const params = {
	  createBy: 0,
	  createTime: "",
	  refundAmount: 0,
	  requestId: null,
	  requestTime: "",
	  reservationId: selectedOrder.value.reservationId,
	  status: "",
	  updateBy: 0,
	  updateTime: "",
	  userId: customerId.value
  }
  console.log(params);
  try {
    const response = await createCancellationRequests(params)
    
    if(response.flag) {
      cancelling.value = false
      cancelDialogVisible.value = false
      ElMessage.success('成功提交取消订单请求，请等待审核')
      fetchOrderList()
    } else {
      cancelling.value = false
      ElMessage.error(response.reason || '取消预订请求提交失败')
    }
  } catch(error) {
    cancelling.value = false
    ElMessage.error('网络错误：' + error.message)
    console.error("取消预订错误:", error)
  }
}
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 24px;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

.pay-amount {
  font-size: 16px;
  margin-bottom: 16px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.pay-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}
</style> 